﻿using System;
using System.Linq;
using System.Web.Mvc;
using Autofac.Integration.Mvc;
using SlamCms.Common;
using SlamCms.Configuration;
using SlamCms.Data;
using SlamCms.Tracking;

namespace SlamCms.Web
{
	[ModelBinderType(typeof(TagBrowserParameters))]
	public class TagBrowserParametersModelBinder : IModelBinder
	{
		public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			var tagBrowserId = (controllerContext.RouteData.Values["TagBrowserId"] ?? string.Empty).ToString();

			if (tagBrowserId.IsNullOrWhiteSpace())
				return null;

			var tagBrowser = TagBrowsers.Browsers.FirstOrDefault(tb => tb.Id == tagBrowserId);

			if (tagBrowser == null)
				return null;

			var tagsString = (controllerContext.RouteData.Values["tags"] ?? string.Empty).ToString().ToLowerInvariant();
			var tags = tagsString.Split(@"/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();

			// check if there is a page number
			int pageNumber = 1;
			if (tags.Count > 0 && int.TryParse(tags.Last(), out pageNumber))
				tags.RemoveAt(tags.Count - 1);
			else
				pageNumber = 1;

			var tagBrowserParameters = new TagBrowserParameters()
			{
				TagBrowser = tagBrowser,
				FilteredTags = tags.ToArray(),
				LastFilteredTag = tags.LastOrDefault(),
				IsLanding = tags.Count == 0,
				PageNumber = pageNumber
			};

			// track tag hits
			if (ConfigurationHelpers.GetEnvironmentSetting(Constants.Settings.TrackingEnabled, true))
			{
				var trackingService = DependencyResolver.Current.GetService<ITrackingService>();
				trackingService.TrackTagHits(tagBrowserParameters.FilteredTags);
			}

			return tagBrowserParameters;
		}
	}
}